import requests
from bs4 import BeautifulSoup
from urllib import parse

if __name__ == "__main__":
    # 对首页的页面数据进行爬取
    url = 'https://www.shicimingju.com/book/sanguoyanyi.html'

    heads = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
    }

    # 关于\x开头的字符串编码转换中文解决方法，https://blog.csdn.net/YungGuo/article/details/110197818
    page_text = requests.get(url=url, headers=heads).text.encode('unicode_escape').decode('utf-8').replace('\\x', '%')
    page_content = parse.unquote(page_text)
    # 在首页解析出章节标题 和 详情页的 url
    # 1. 实例化 BeautifulSoup 对象，需要将页面源码数据加载到该对象中
    soup = BeautifulSoup(page_content, 'lxml')

    # 解析章节标题和详情页的 url
    li_list = soup.select('.book-mulu > ul > li')
    fp = open('爬取文件/三国.txt', 'w', encoding='utf-8')
    for li in li_list:
        title = li.a.string
        detail_url = 'https://www.shicimingju.com/' + li.a['href']

        # 对详情页发起请求，解析出章节内容
        detailPage_text = requests.get(url=detail_url, headers=heads).text.encode('unicode_escape').decode('utf-8').replace('\\x', '%')
        page_detail_content = parse.unquote(detailPage_text)
        # 解析出详情页中相关的章节内容
        detail_soup = BeautifulSoup(page_detail_content, 'lxml')
        div_tag = detail_soup.find('div', class_='chapter_content')
        # 解析到了章节的内容
        content = div_tag.text
        fp.write(title + ": \n" + content + "\n")
        print(title + ": " + content + "\n")

    fp.close()